#!/usr/local/bin/python3.7
import pymysql
import time
import sys
import os
import logging
from configparser import ConfigParser
import json
import pandas
import datetime
import random
from DrissionPage import WebPage,ChromiumPage,ChromiumOptions,SessionPage

logging.basicConfig(filename='myapp.log', level=logging.ERROR)
logger = logging.getLogger(__name__)

#path = r'C:\Program Files\Google\Chrome\Application\Chrome.exe'  # 请改为你电脑内Chrome可执行文件路径
#path = r'/usr/bin/chrome-google-stable'  # 请改为你电脑内Chrome可执行文件路径
base_path = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_path, 'config.ini')
print('file_path',file_path)
config = ConfigParser()
config.read(file_path)
path = config.get('server','chrome_path')

ChromiumOptions().set_browser_path(path).save()
#co = ChromiumOptions().headless() #无头浏览器
#page = ChromiumPage(co)
# co = ChromiumOptions().set_local_port(9222)
# page = ChromiumPage(addr_or_opts=co)
page = ChromiumPage()
pageSession = SessionPage()

argv_path = sys.argv[0]
if ((os.path.isfile(argv_path))):
    print(argv_path + ' 已找到，开始执行...')
else:
    print('File not exist!!!')
    sys.exit()

startTime = time.time()  # 计时开始
print('计时开始，当前时间为', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(startTime)))

def login():
    loginUrl = config.get('server','login_url')
    # 加载界面
    page.get(loginUrl)

    # 监听数据包特征
    simple = ['/quickbuy/v1/poi/sputag/products', '/quickbuy/v1/poi/product/smooth/render']
    page.listen.start(simple)
    
    wait = config.getint('setting','wait_seconds')
    print(f"进入登录页面等待{wait}s...")
    page.wait(wait)

    # for i in page.cookies(as_dict=False, all_domains=True):
    #     print(i)
    # 清空cookie
    # cookie_items = pageSession.set.cookies.clear()
    
    #截图保存路径
    save_path = config.get('setting', 'login_screenshot_path')
    
    #如果是已登录状态，则直接退出登录并关闭页面
    # try:
    #     loaded = page.wait.eles_loaded(config.get('target','username_ele'), 30, True, True)
    #     #displayed = page.wait.ele_displayed(config.get('target','username_ele'), timeout=None, raise_err=True)
    #     if loaded == False:
    #         print('已登录，退出页面...')
    #         page.get_screenshot(path=save_path, name='islogin.jpg', full_page=True)
    #         #page.quit()
    #         sys.exit()
    # except Exception as e:
    #     # 截图保存
    #     logger.error('异常信息：', exc_info=True)
    #     page.get_screenshot(path=save_path, name='islogin.jpg', full_page=True)
    #     print('已登录，退出页面...')
    #     #page.quit()
    #     sys.exit()
        
    # 定位到账号文本框，获取文本框元素
    # username = page.ele(config.get('target','username_ele'))
    # # 输入对文本框输入账号
    # username.input(config.get('target','account'))
    # # 定位到密码文本框并输入密码
    # password = page.ele(config.get('target','password_ele'))
    # # 输入对文本框输入密码
    # password.input(config.get('target','password'))
    # # 点击登录按钮
    # page.ele(config.get('target','submit_button')).click()

    # page.wait.load_start()

    # print(f"执行登录等待{wait}s...")
    # page.wait(wait)
    
    save_name = config.get('setting', 'login_screenshot_name')
    # 截图保存
    page.get_screenshot(path=save_path, name=save_name, full_page=True)

    # 获取页面数据打印
    getLists()

    print("滚动到底部")
    page.ele('#spuScroll').scroll.to_bottom()
    res = page.listen.wait()  # 等待并获取一个数据包
    print(res.url)
    print(res.request.headers)
    print(res.request.cookies)
    print(res.response.body)
    saveRequestHeaders(res.request.headers)
    saveRequestCookies(res.request.cookies)
    savePostData(res.request.postData)
    saveResponseBody(res.response.body)

    #获取cookie
    # cookie_str = ''
    # cookie_items = page.cookies(as_dict=False, all_domains=True)
    # #组装cookie字符串
    # for item_cookie in cookie_items:
    #     item_str = item_cookie["name"]+"="+item_cookie["value"]+"; "
    #     cookie_str += item_str
    #     if item_cookie["name"] == 'session':
    #         session = item_cookie["value"]
    #         print('session：',item_cookie["value"])
    # #保存到数据库
    # updateMysql(cookie_str)
    # #打印出来看一下
    # file = open(config.get('setting', 'cookie_file_name'),'w')
    # file.write(cookie_str)
    # file.close()
    #page.quit()
       
def getconfig(type, key):
    # 创建一个解析器对象
    config = ConfigParser()
    
    # 读取配置文件
    config.read('config.ini')
    return config.get(type, key)
    
def updateMysql(session):
    dbconfig = dict(config.items('database'))
    # 数据库连接
    db = pymysql.connect(**dbconfig)

    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()

    # SQL 更新语句
    sql = "UPDATE ht_set SET `value` = '" + session + "' WHERE `key` = 'cookie'"
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        # 发生错误时回滚
        db.rollback()

    # 关闭数据库连接
    db.close()
def getLists():
    # 获取文本框元素
    boxs_ele = page.ele('#leftTab')

    # 获取该 ul 元素下所有 a 元素
    titles = boxs_ele.eles('.p-cat-box')  

    # 遍历列表，打印每个 a 元素的文本
    for i in titles:  
        print(i.text)

def saveRequestHeaders(data):
    with open('headers.txt', 'w') as file:
        for key, value in data.items():
            file.write(f'{key}: {value}\n')

def readRequestHeaders():
    with open('headers.txt', 'r') as file:
        read_data = file.read()
        print(read_data)

def saveRequestCookies(data):
    # 将列表字典转换为JSON格式的字符串
    data_json = json.dumps(data, ensure_ascii=False)
    # 将字符串写入文件
    with open('cookies.txt', 'w') as file:
        file.write(data_json)

def savePostData(dict_data):
    # 写入文件
    with open('postData.txt', 'w', encoding='utf-8') as file:
        file.write(str(dict_data) + '\n')

def saveResponseBody(dict_data):
    # 将字典转换为JSON格式的字符串
    json_string = json.dumps(dict_data, ensure_ascii=False)
    with open('responseBody.txt', 'w', encoding='utf-8') as file:
        file.write(json_string + '\n')

def exportExcel(data):
    df = pandas.DataFrame(data)
    fileName = generate_random_filename()
    df.to_excel(fileName+'.xlsx', index=False)

def generate_random_filename():
    # 获取当前日期
    now = datetime.datetime.now()
    # 格式化日期为字符串
    date_str = now.strftime("%Y%m%d")
    # 生成随机数作为文件名的一部分
    random_number = random.randint(100000, 999999)
    # 生成文件名
    filename = f"{date_str}_{random_number}"
    return filename

login()
# 在代码的最后添加这一行
input("Press Enter to exit...")